package com.simpleframe.views.ui;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;

import com.simpleframe.security.AuthorityContext;
import com.simpleframe.security.User;

/**
 * 	<g:auth>
 *  		1
 *		<g:auth url="" /> 
 *	  		2
 *		<g:auth /> 
 *	  		3
 *	</g:auth>
 * @author gan
 *
 */
public class AuthTag extends BodyTagSupport {

	private static final long serialVersionUID = 1L;

	private String url;
	private boolean hasAuth = true;

	@Override
	public int doStartTag() throws JspException {
		hasAuth = true;
		HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
		User user = (User)request.getSession().getAttribute(User.USER_SESSION);
		System.out.println(url);
		if(AuthorityContext.isProtectResource(url)){
			System.out.println("---");
			if(!AuthorityContext.verifyOperate(user.getRoleIds(), url)){
				hasAuth = false;
				System.out.println("false");
				Tag parent = getParent();
				if (parent != null && parent instanceof AuthTag) {
					System.out.println("parent false");
					AuthTag authTag = (AuthTag) parent;
					authTag.setHasAuth(false);
				}
			}
		}
		
		return EVAL_BODY_BUFFERED;
	}

	@Override
	public int doEndTag() throws JspException {
		try {
			if (hasAuth)
				pageContext.getOut().write(bodyContent.getString().trim());
		} catch (IOException e) {
			throw new JspException("IOError while writing the body: "
					+ e.getMessage(), e);
		}
		return super.doEndTag();
	}
	
	public void setUrl(String url) {
		this.url = url;
	}
	
	public void setHasAuth(boolean hasAuth) {
		this.hasAuth = hasAuth;
	}
//
//	private String body = null; // 用于存放成功条件后的内容
////
//	public void setBody() {
//		if (body == null) {
//			body = bodyContent.getString().trim();
//		}
//	}
////
//	private String getBody() {
//		if (body == null)
//			return bodyContent.getString().trim();
//		else
//			return body;
//	}
//
//	/**
//	 * 判断if 或者 子 else if是否提交成功
//	 */
//	private boolean subtagSucceeded;
//
//	/**
//	 * 子条件判断成功
//	 */
//	public void succeeded() {
//		subtagSucceeded = true;
//	}
//
//	/**
//	 * 是否已经执行完毕
//	 * 
//	 * @return
//	 */
//	public boolean isSucceeded() {
//		return subtagSucceeded;
//	}
//
//	private void init() {
//		test = false;
//		subtagSucceeded = false;
//		body = null;
//	}
//
//	private boolean test;
//
//	public void setTest(boolean test) {
//		this.test = test;
//	}
}
